//
//  HGCamera.m
//  HGMM
//
//  Created by @HUI on 15/9/16.
//  Copyright (c) 2015年 cc. All rights reserved.
//

#import "HGCamera.h"
#import "HGPluginViewController.h"
#import "CameraViewController.h"
#import "ZZCameraController.h"
#import "UIView+ViewController.h"
#import "ZZCamera.h"
#import "NSString+hui.h"
#import "HGPluginUtil.h"
#import "NSArray+Json.h"
#import "ZZPhotoKit.h"

typedef void(^ImageBlock)(NSArray *array);


@interface HGCamera ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    UILabel *lable;
    
}

@property(nonatomic,copy)ImageBlock imageBlock1;
@property(nonatomic,copy)ImageBlock imageBlock2;


@end

@implementation HGCamera

-(void)getPic:(CDVInvokedUrlCommand *)command{
    __block CDVPluginResult *pluginResult = nil;
    if (command.arguments.count !=3 || ![command.arguments[0] isKindOfClass:[NSString class]] || ![command.arguments[1] isKindOfClass:[NSString class]] || ![command.arguments[2] isKindOfClass:[NSString class]]) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    HGPluginViewController *vc;
    if ([self.viewController isKindOfClass:[HGPluginViewController class]]) {
        vc = (HGPluginViewController *)self.viewController;
       
        dispatch_async(dispatch_get_main_queue(), ^{
            
            CameraViewController *camera = [[CameraViewController alloc]initWithBlock:^(NSArray *arr) {
                
                NSString *resultString = [arr toReadableJSONString];
                
                
                CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:resultString];
                
                [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                
            }];
            camera.lableText1 = command.arguments[0];
            camera.lableText2 = command.arguments[1];
            camera.path = command.arguments[2];
            camera.pluginId = Plugin_IN;
            
            [self.webView.viewContoller presentViewController:camera animated:YES completion:^{
                
            }];
            
        });
    }

}


-(void)getPicCompress:(CDVInvokedUrlCommand *)command{
    
    __block CDVPluginResult *pluginResult = nil;
    if (command.arguments.count !=4 || ![command.arguments[0] isKindOfClass:[NSString class]] || ![command.arguments[1] isKindOfClass:[NSString class]] || ![command.arguments[2] isKindOfClass:[NSString class]] ) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    NSString *label1 = command.arguments[0];
    NSString *label2 = command.arguments[1];
    NSString *path = command.arguments[2];
    id quality = command.arguments[3];
    CGFloat qy = ([quality integerValue] + 1) * 0.1;
    
    
    NSString *wString = [NSString stringWithFormat:@"%@\n%@",label1,label2];
    
    ZZCameraController *cameraController = [[ZZCameraController alloc]init];
    cameraController.takePhotoOfMax = 8;
    cameraController.waterString = wString;
    
    cameraController.isSaveLocal = NO;
    
    HGPluginViewController *vc = (HGPluginViewController *)self.viewController;
   
    
    [cameraController showIn:self.webView.viewContoller result:^(id responseObject){
        
     
        NSMutableArray *mutaArray = [NSMutableArray array];
        
        for (ZZCamera *zz in responseObject) {
            
            UIImage *orgImage = zz.image;
            NSData *data = UIImageJPEGRepresentation(orgImage, qy);
            UIImage *resultImage = [UIImage imageWithData:data];
            [mutaArray addObject:resultImage];
        }
        
        NSArray *result =[self saveImageWithImages:mutaArray pluginId:Plugin_IN path:path];
        
        NSString *resultString = [result toReadableJSONString];
       
        
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:resultString];
        
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
    }];
}


-(NSArray *)saveImageWithImages:(NSArray *)imageArr  pluginId:(NSString *)pluginId path:(NSString *)path{
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
    NSString *imgName = [NSString stringWithCurrentDate];
    HGPluginUtil *util = [[HGPluginUtil alloc]init];
    NSString *rootPath = [[NSString stringWithFormat:@"%@/image",[util getPluginDataDir:pluginId]]stringByAppendingPathComponent:path];
    NSError *error = nil;
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:rootPath]) {
        [manager createDirectoryAtPath:rootPath withIntermediateDirectories:YES attributes:nil error:&error];
        if (error) {
            return nil;
        }
    }
    for (int i = 0; i < imageArr.count; i++) {
        NSString *imgPath = [NSString stringWithFormat:@"%@_%d.jpg",imgName, i];
        NSString *savePath = [rootPath stringByAppendingPathComponent:imgPath];
        NSData *imgData = UIImageJPEGRepresentation(imageArr[i], 1);
        [imgData writeToFile:savePath atomically:YES];
        [arr addObject:savePath];
    }

    return arr;
}


-(void)cropCamera:(CDVInvokedUrlCommand *)command{
    
   UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.delegate = self;
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;//获取类型是摄像头，还可以是相册
    
    imagePicker.allowsEditing = NO;
   imagePicker.cameraViewTransform = CGAffineTransformScale(imagePicker.cameraViewTransform, 0.7, 0.5);
    
    [self.webView.viewContoller presentViewController:imagePicker animated:YES completion:nil];
    
    
    //HGPluginViewController *vc = (HGPluginViewController *)self.viewController;
   
    
    __weak HGCamera *weakSelf = self;
    
    //回调
    self.imageBlock1 = ^(NSArray *array){
      
        NSArray *result = [weakSelf saveImageWithImages:array pluginId:Plugin_IN path:@"la/cc"];
        NSString *resultString = [result toReadableJSONString];
        
        
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:resultString];
        
        [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
        
    };
  
    
}


-(void)cropImage:(CDVInvokedUrlCommand *)command{
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.delegate = self;
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;//获取类型是摄像头，还可以是相册
    
    imagePicker.allowsEditing = YES;
   // imagePicker.cameraViewTransform = CGAffineTransformScale(imagePicker.cameraViewTransform, 0.7, 0.5);
    
    [self.webView.viewContoller presentViewController:imagePicker animated:YES completion:nil];
    
    /*
    HGPluginViewController *vc = (HGPluginViewController *)self.viewController;
    if (!vc.rootViewController) {
        return;
    }
    */
    
    __weak HGCamera *weakSelf = self;
    
    //回调
    self.imageBlock2 = ^(NSArray *array){
        
        NSArray *result = [weakSelf saveImageWithImages:array pluginId:Plugin_IN path:@"la/cc"];
        NSString *resultString = [result toReadableJSONString];
        
        
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:resultString];
        
        [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
        
    };
    
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:@"public.image"]) { //选择了图片
        
        UIImage *image;
        
        if ([info objectForKey:UIImagePickerControllerEditedImage])
        {
            
            image = [info objectForKey:UIImagePickerControllerEditedImage];
        }
        else if ([info objectForKey:UIImagePickerControllerOriginalImage])
        {
            
            image = [info objectForKey:UIImagePickerControllerOriginalImage];
            
        }
        
        NSArray *array = [NSArray arrayWithObject:image];
        
        if (self.imageBlock1) {
            
            self.imageBlock1(array);
        }
        
        if (self.imageBlock2) {
            
            self.imageBlock2(array);
        }
        
    }
    
    [self.webView.viewContoller dismissViewControllerAnimated:YES completion:nil];
    
}





-(void)getPictureByAlbum:(CDVInvokedUrlCommand *)command{
    
    
    if (command.arguments.count !=1) {
        CDVPluginResult  *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    CGFloat qu = (CGFloat)([(NSNumber *)command.arguments[0] integerValue] * 0.14);
    
    ZZPhotoController *photoController = [[ZZPhotoController alloc]init];
    
    
    
    //设置最大选择张数
    
    photoController.selectPhotoOfMax = 9;
    
    
    
    [photoController showIn:self.webView.viewContoller result:^(id responseObject){
        
        
        //返回结果集
        HGLog(@"%@",responseObject);
        
        NSArray *array = (NSArray *)responseObject;
        
        if (array.count == 0) {
            
            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"图库选取失败"];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            
            return;
        }
        
        NSMutableArray *mutaArray = [NSMutableArray array];
        
        for (ZZPhoto *zz in array) {
            
            UIImage *zImage = zz.originImage;
            
            NSData *data = UIImageJPEGRepresentation(zImage,qu);
            
            NSString *base64Str = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
            
            [mutaArray addObject:base64Str];
            
        }
        
        NSString *result = [mutaArray toReadableJSONString];
        
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
    }];
    
}










@end
